import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isUndefined from "lodash/isUndefined";
import _isEmpty from "lodash/isEmpty";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _dec14, _dec15, _dec16, _dec17, _dec18, _class, _class2;

/**
 * 任务执行器
 * @date: 2018-9-3


 */
import React, { Component } from 'react';
import { Form, Popconfirm, Table, Tag } from 'antd';
import { connect } from 'dva';
import { Bind } from 'lodash-decorators';
import { Content, Header } from 'components/Page';
import { Button as ButtonPermission } from 'components/Permission';
import formatterCollections from 'utils/intl/formatterCollections';
import intl from 'utils/intl';
import { addressTypeRender, operatorRender } from 'utils/renderer';
import notification from 'utils/notification';
import { filterNullValueObject, getEditTableData, isTenantRoleLevel, tableScrollWidth } from 'utils/utils';
import JobGroupForm from "./JobGroupForm";
import ExecutorDrawer from "./ExecutorDrawer.js";
import SearchForm from "./SearchForm";
/**
 * 任务执行器
 * @extends {Component} - React.Component
 * @reactProps {Object} [location={}] - 当前路由信息
 * @reactProps {Object} [match={}] - react-router match路由信息
 * @reactProps {!Object} jobGroup - 数据源
 * @reactProps {!Object} loading - 数据加载是否完成
 * @reactProps {Object} form - 表单对象
 * @reactProps {Function} [dispatch=function(e) {return e;}] - redux dispatch方法
 * @return React.element
 */

var JobGroup = (_dec = connect(function (_ref) {
  var jobGroup = _ref.jobGroup,
      loading = _ref.loading;
  return {
    jobGroup: jobGroup,
    tenantRoleLevel: isTenantRoleLevel(),
    saving: loading.effects['jobGroup/updateGroups'],
    creating: loading.effects['jobGroup/createGroups'],
    fetchList: loading.effects['jobGroup/fetchGroupsList'],
    fetchExecutorLoading: loading.effects['jobGroup/fetchExecutorList'],
    deleteExecutorLoading: loading.effects['jobGroup/deleteExecutor'],
    saveExecutorLoading: loading.effects['jobGroup/updateExecutor']
  };
}), _dec2 = Form.create({
  fieldNameProp: null
}), _dec3 = formatterCollections({
  code: ['csdr.jobGroup', 'entity.tenant']
}), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec14 = Bind(), _dec15 = Bind(), _dec16 = Bind(), _dec17 = Bind(), _dec18 = Bind(), _dec(_class = _dec2(_class = _dec3(_class = (_class2 = /*#__PURE__*/function (_Component) {
  _inherits(JobGroup, _Component);

  var _super = _createSuper(JobGroup);

  function JobGroup(props) {
    var _this;

    _classCallCheck(this, JobGroup);

    _this = _super.call(this, props);
    _this.state = {
      groupsData: {},
      selectExecutorRecord: {},
      executorModalVisible: false
    };
    return _this;
  }
  /**
   * render()调用后获取数据
   */


  _createClass(JobGroup, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var dispatch = this.props.dispatch;
      dispatch({
        type: 'jobGroup/init'
      });
      this.fetchGroupsList();
    }
    /**
     * 查询
     * @param {object} fields - 查询参数
     */

  }, {
    key: "fetchGroupsList",
    value: function fetchGroupsList() {
      var fields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var dispatch = this.props.dispatch;
      var filterValues = _isUndefined(this.form) ? {} : filterNullValueObject(this.form.getFieldsValue());
      dispatch({
        type: 'jobGroup/fetchGroupsList',
        payload: _objectSpread({
          page: _isEmpty(fields) ? {} : fields
        }, filterValues)
      });
    }
    /**
     * @function showModal - 新增显示模态框
     */

  }, {
    key: "showModal",
    value: function showModal() {
      var _this2 = this;

      this.setState({
        groupsData: {}
      }, function () {
        _this2.handleModalVisible(true);
      });
    }
    /**
     * @function handleModalVisible - 控制modal显示与隐藏
     * @param {boolean} flag 是否显示modal
     */

  }, {
    key: "handleModalVisible",
    value: function handleModalVisible(flag) {
      var dispatch = this.props.dispatch;
      dispatch({
        type: 'jobGroup/updateState',
        payload: {
          modalVisible: !!flag
        }
      });
    }
  }, {
    key: "handleModalSave",
    value: function handleModalSave(fieldsValue) {
      var _this3 = this;

      var _this$props = this.props,
          dispatch = _this$props.dispatch,
          pagination = _this$props.jobGroup.pagination;
      var _this$state$groupsDat = this.state.groupsData,
          groupsData = _this$state$groupsDat === void 0 ? {} : _this$state$groupsDat; // if (groupsData.executorType !== 0) {

      dispatch({
        type: "jobGroup/".concat(groupsData.executorId ? 'updateGroups' : 'createGroups'),
        payload: _objectSpread(_objectSpread({
          executorType: 1
        }, groupsData), fieldsValue)
      }).then(function (res) {
        if (res) {
          notification.success();

          _this3.handleModalVisible(false);

          _this3.fetchGroupsList(pagination);
        }
      }); // } else {
      //   this.handleModalVisible(false);
      // }
    }
    /**
     * @function handleUpdateEmail - 编辑
     * @param {object} record - 头数据
     */

  }, {
    key: "handleUpdateGroups",
    value: function handleUpdateGroups(record) {
      this.setState({
        groupsData: record
      });
      this.handleModalVisible(true);
    }
  }, {
    key: "showExecutorModal",
    value: function showExecutorModal(flag) {
      this.setState({
        executorModalVisible: flag
      });
    }
  }, {
    key: "handleCancelExecutor",
    value: function handleCancelExecutor() {
      this.showExecutorModal(false);
    }
  }, {
    key: "handleSaveExecutor",
    value: function handleSaveExecutor() {
      var _this4 = this;

      var _this$props2 = this.props,
          dispatch = _this$props2.dispatch,
          _this$props2$jobGroup = _this$props2.jobGroup,
          jobGroup = _this$props2$jobGroup === void 0 ? {} : _this$props2$jobGroup;
      var _jobGroup$executorLis = jobGroup.executorList,
          executorList = _jobGroup$executorLis === void 0 ? [] : _jobGroup$executorLis;
      var params = getEditTableData(executorList, ['executorId']);

      if (Array.isArray(params) && params.length > 0) {
        dispatch({
          type: 'jobGroup/updateExecutor',
          payload: params
        }).then(function (res) {
          if (res) {
            notification.success();

            _this4.fetchExecutorList();
          }
        });
      }
    }
    /**
     * 删除执行器配置
     */

  }, {
    key: "handleDeleteExecutor",
    value: function handleDeleteExecutor() {
      var _this5 = this;

      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var _this$props3 = this.props,
          dispatch = _this$props3.dispatch,
          _this$props3$jobGroup = _this$props3.jobGroup.executorList,
          executorList = _this$props3$jobGroup === void 0 ? [] : _this$props3$jobGroup;
      var filterData = data.filter(function (item) {
        return item._status !== 'create';
      }); // 删除未保存的数据

      var createList = data.filter(function (item) {
        return item._status === 'create';
      });

      if (createList.length > 0) {
        var deleteList = executorList.filter(function (item) {
          return !keys.includes(item.executorId);
        });
        dispatch({
          type: 'jobGroup/updateState',
          payload: {
            executorList: deleteList
          }
        });
        notification.success();
      }

      if (filterData.length > 0) {
        dispatch({
          type: 'jobGroup/deleteExecutor',
          payload: filterData
        }).then(function (res) {
          if (res) {
            notification.success();

            _this5.fetchExecutorList();
          }
        });
      }
    }
  }, {
    key: "handleEditExecutor",
    value: function handleEditExecutor(record, flag) {
      var _this$props4 = this.props,
          _this$props4$jobGroup = _this$props4.jobGroup.executorList,
          executorList = _this$props4$jobGroup === void 0 ? [] : _this$props4$jobGroup,
          dispatch = _this$props4.dispatch;
      var newList = executorList.map(function (item) {
        if (record.uuid === item.uuid) {
          return _objectSpread(_objectSpread({}, item), {}, {
            _status: flag ? 'update' : ''
          });
        }

        return item;
      });
      dispatch({
        type: 'jobGroup/updateState',
        payload: {
          executorList: newList
        }
      });
    }
    /**
     * 执行器配置
     */

  }, {
    key: "handleExecutorConfig",
    value: function handleExecutorConfig(record) {
      var _this6 = this;

      this.showExecutorModal(true);
      this.setState({
        selectExecutorRecord: record
      }, function () {
        _this6.fetchExecutorList();
      });
    }
    /**
     * 获取执行器配置列表
     * @param {object} params - 查询参数
     */

  }, {
    key: "fetchExecutorList",
    value: function fetchExecutorList(params) {
      var dispatch = this.props.dispatch;
      var _this$state$selectExe = this.state.selectExecutorRecord,
          selectExecutorRecord = _this$state$selectExe === void 0 ? {} : _this$state$selectExe;
      var executorId = selectExecutorRecord.executorId; // 清空缓存

      dispatch({
        type: 'jobGroup/updateState',
        payload: {
          executorList: []
        }
      });
      dispatch({
        type: 'jobGroup/fetchExecutorList',
        payload: _objectSpread(_objectSpread({}, params), {}, {
          executorId: executorId
        })
      });
    }
    /**
     * 数据列表，头删除
     * @function handleDeleteGroups
     * @param {obejct} record - 操作对象
     */

  }, {
    key: "handleDeleteGroups",
    value: function handleDeleteGroups(record) {
      var _this7 = this;

      var _this$props5 = this.props,
          dispatch = _this$props5.dispatch,
          pagination = _this$props5.jobGroup.pagination;
      dispatch({
        type: 'jobGroup/deleteGroups',
        payload: record
      }).then(function (res) {
        if (res) {
          notification.success();

          _this7.fetchGroupsList(pagination);
        }
      });
    }
    /**
     * 传递表单对象
     * @param {object} ref - FilterForm对象
     */

  }, {
    key: "handleBindRef",
    value: function handleBindRef() {
      var ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.form = (ref.props || {}).form;
    }
    /**
     * 更改上下线状态
     * @param {object} record
     * @param {boolean} isOffLine
     * @memberof JobGroup
     */

  }, {
    key: "handleChangeStatus",
    value: function handleChangeStatus(record, isOffLine) {
      var _this8 = this;

      var _this$props6 = this.props,
          dispatch = _this$props6.dispatch,
          pagination = _this$props6.jobGroup.pagination;
      dispatch({
        type: 'jobGroup/updateGroups',
        payload: _objectSpread(_objectSpread({
          executorType: 1
        }, record), {}, {
          status: isOffLine ? 'ONLINE' : 'OFFLINE'
        })
      }).then(function (res) {
        if (res) {
          notification.success();

          _this8.fetchGroupsList(pagination);
        }
      });
    }
    /**
     * render
     * @returns React.element
     */

  }, {
    key: "render",
    value: function render() {
      var _this9 = this;

      var _this$props7 = this.props,
          fetchList = _this$props7.fetchList,
          saving = _this$props7.saving,
          creating = _this$props7.creating,
          tenantRoleLevel = _this$props7.tenantRoleLevel,
          path = _this$props7.match.path,
          _this$props7$saveExec = _this$props7.saveExecutorLoading,
          saveExecutorLoading = _this$props7$saveExec === void 0 ? false : _this$props7$saveExec,
          _this$props7$deleteEx = _this$props7.deleteExecutorLoading,
          deleteExecutorLoading = _this$props7$deleteEx === void 0 ? false : _this$props7$deleteEx,
          _this$props7$fetchExe = _this$props7.fetchExecutorLoading,
          fetchExecutorLoading = _this$props7$fetchExe === void 0 ? false : _this$props7$fetchExe,
          _this$props7$jobGroup = _this$props7.jobGroup,
          groupsList = _this$props7$jobGroup.groupsList,
          modalVisible = _this$props7$jobGroup.modalVisible,
          pagination = _this$props7$jobGroup.pagination,
          statusList = _this$props7$jobGroup.statusList,
          _this$props7$jobGroup2 = _this$props7$jobGroup.executorList,
          executorList = _this$props7$jobGroup2 === void 0 ? [] : _this$props7$jobGroup2;
      var _this$state = this.state,
          executorId = _this$state.groupsData.executorId,
          executorModalVisible = _this$state.executorModalVisible,
          selectExecutorRecord = _this$state.selectExecutorRecord;
      var jobGroupFormProps = {
        saving: saving,
        creating: creating,
        modalVisible: modalVisible,
        statusList: statusList,
        tenantRoleLevel: tenantRoleLevel,
        modalTitle: executorId ? intl.get('csdr.jobGroup.view.message.edit').d('编辑执行器') : intl.get('csdr.jobGroup.view.message.create').d('新增执行器'),
        initData: this.state.groupsData,
        onCancel: function onCancel() {
          return _this9.handleModalVisible(false);
        },
        onOk: this.handleModalSave
      };
      var filterProps = {
        onSearch: this.fetchGroupsList,
        onRef: this.handleBindRef
      };
      var executorProps = {
        selectExecutorRecord: selectExecutorRecord,
        path: path,
        modalVisible: executorModalVisible,
        saveLoading: saveExecutorLoading,
        deleteLoading: deleteExecutorLoading,
        initLoading: fetchExecutorLoading,
        dataSource: executorList,
        onEdit: this.handleEditExecutor,
        onDelete: this.handleDeleteExecutor,
        onOk: this.handleSaveExecutor,
        onCancel: this.handleCancelExecutor
      };
      var columns = [{
        title: intl.get('csdr.jobGroup.model.jobGroup.orderSeq').d('排序'),
        dataIndex: 'orderSeq',
        width: 80
      }, {
        title: intl.get('csdr.jobGroup.model.jobGroup.executorCode').d('执行器编码'),
        dataIndex: 'executorCode',
        width: 200
      }, {
        title: intl.get('csdr.jobGroup.model.jobGroup.executorName').d('执行器名称'),
        dataIndex: 'executorName',
        width: 150
      }, {
        title: intl.get('csdr.jobGroup.model.jobGroup.addressType').d('注册方式'),
        dataIndex: 'executorType',
        width: 120,
        render: addressTypeRender
      }, {
        title: intl.get('csdr.jobGroup.view.message.serverName').d('服务'),
        dataIndex: 'serverName',
        width: 170
      }, {
        title: intl.get('csdr.jobGroup.model.jobGroup.status').d('状态'),
        dataIndex: 'statusMeaning',
        width: 120,
        render: function render(text, record) {
          var color;

          switch (record.status) {
            case 'ONLINE':
              color = 'green';
              break;

            case 'OFFLINE':
              color = 'orange';
              break;

            case 'A-OFFLINE':
              color = 'red';
              break;

            default:
              return;
          }

          return /*#__PURE__*/React.createElement(Tag, {
            color: color
          }, text);
        }
      }, {
        title: intl.get('csdr.jobGroup.model.jobGroup.addressList').d('OnLine 机器地址'),
        dataIndex: 'addressList'
      }, {
        title: intl.get('cpaas.common.button.action').d('操作'),
        dataIndex: 'operator',
        width: 200,
        fixed: 'right',
        render: function render(val, record) {
          var status = record.status;
          var isOffLine = status === 'OFFLINE';
          var operators = [];
          operators.push({
            key: 'executor',
            ele: /*#__PURE__*/React.createElement(ButtonPermission, {
              type: "text",
              permissionList: [{
                code: "".concat(path, ".button.executor"),
                type: 'button',
                meaning: '执行器管理-配置'
              }],
              onClick: function onClick() {
                return _this9.handleExecutorConfig(record);
              }
            }, intl.get('csdr.jobGroup.button.executor').d('配置')),
            len: 2,
            title: intl.get('csdr.jobGroup.button.executor').d('配置')
          }, {
            key: 'changeStatus',
            ele: /*#__PURE__*/React.createElement(ButtonPermission, {
              type: "text",
              permissionList: [{
                code: "".concat(path, ".button.changeStatus"),
                type: 'button',
                meaning: '执行器管理-更改状态'
              }],
              onClick: function onClick() {
                return _this9.handleChangeStatus(record, isOffLine);
              }
            }, isOffLine ? intl.get('csdr.jobGroup.button.onLine').d('上线') : intl.get('csdr.jobGroup.button.offLine').d('下线')),
            len: 2,
            title: isOffLine ? intl.get('csdr.jobGroup.button.onLine').d('上线') : intl.get('csdr.jobGroup.button.offLine').d('下线')
          }, {
            key: 'edit',
            ele: /*#__PURE__*/React.createElement(ButtonPermission, {
              type: "text",
              permissionList: [{
                code: "".concat(path, ".button.edit"),
                type: 'button',
                meaning: '执行器管理-编辑'
              }],
              onClick: function onClick() {
                return _this9.handleUpdateGroups(record);
              }
            }, intl.get('cpaas.common.button.edit').d('编辑')),
            len: 2,
            title: intl.get('cpaas.common.button.edit').d('编辑')
          }, {
            key: 'delete',
            ele: /*#__PURE__*/React.createElement(Popconfirm, {
              placement: "topRight",
              title: intl.get('cpaas.common.message.confirm.delete').d('是否删除此条记录？'),
              onConfirm: function onConfirm() {
                return _this9.handleDeleteGroups(record);
              }
            }, /*#__PURE__*/React.createElement(ButtonPermission, {
              type: "text",
              permissionList: [{
                code: "".concat(path, ".button.delete"),
                type: 'button',
                meaning: '执行器管理-删除'
              }]
            }, intl.get('cpaas.common.button.delete').d('删除'))),
            len: 2,
            title: intl.get('cpaas.common.button.delete').d('删除')
          });
          return operatorRender(operators, record, {
            limit: 4
          });
        }
      }].filter(function (col) {
        return tenantRoleLevel ? col.dataIndex !== 'tenantName' : true;
      });
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Header, {
        title: intl.get('csdr.jobGroup.view.message.group').d('执行器管理')
      }, /*#__PURE__*/React.createElement(ButtonPermission, {
        type: "primary",
        icon: "plus",
        permissionList: [{
          code: "".concat(path, ".button.create"),
          type: 'button',
          meaning: '执行器管理-新建'
        }],
        onClick: this.showModal
      }, intl.get('cpaas.common.button.create').d('新建'))), /*#__PURE__*/React.createElement(Content, null, /*#__PURE__*/React.createElement(SearchForm, filterProps), /*#__PURE__*/React.createElement(Table, {
        bordered: true,
        rowKey: "executorId",
        loading: fetchList,
        columns: columns,
        scroll: {
          x: tableScrollWidth(columns)
        },
        dataSource: groupsList,
        pagination: pagination,
        onChange: this.fetchGroupsList
      }), modalVisible && /*#__PURE__*/React.createElement(JobGroupForm, jobGroupFormProps), executorModalVisible && /*#__PURE__*/React.createElement(ExecutorDrawer, executorProps)));
    }
  }]);

  return JobGroup;
}(Component), (_applyDecoratedDescriptor(_class2.prototype, "fetchGroupsList", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "fetchGroupsList"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showModal", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "showModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleModalVisible", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleModalVisible"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleModalSave", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "handleModalSave"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleUpdateGroups", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "handleUpdateGroups"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showExecutorModal", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "showExecutorModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleCancelExecutor", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "handleCancelExecutor"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSaveExecutor", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSaveExecutor"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleDeleteExecutor", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "handleDeleteExecutor"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleEditExecutor", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "handleEditExecutor"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleExecutorConfig", [_dec14], Object.getOwnPropertyDescriptor(_class2.prototype, "handleExecutorConfig"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "fetchExecutorList", [_dec15], Object.getOwnPropertyDescriptor(_class2.prototype, "fetchExecutorList"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleDeleteGroups", [_dec16], Object.getOwnPropertyDescriptor(_class2.prototype, "handleDeleteGroups"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleBindRef", [_dec17], Object.getOwnPropertyDescriptor(_class2.prototype, "handleBindRef"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleChangeStatus", [_dec18], Object.getOwnPropertyDescriptor(_class2.prototype, "handleChangeStatus"), _class2.prototype)), _class2)) || _class) || _class) || _class);
export { JobGroup as default };